package com.sicnustray.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sicnustray.common.Constants;
import com.sicnustray.common.Result;
import com.sicnustray.controller.dto.UserDTO;
import com.sicnustray.jwt.JwtUtil;
import com.sicnustray.utils.RedisUtils;
import com.sicnustray.utils.annotation.MyLog;
import com.sicnustray.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.sicnustray.service.IUserService;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yl
 * @since 2022-11-05
 */
@CacheConfig(cacheNames="com.sicnustray.controller.UserController")
@RestController
@RequestMapping("/user")
public class UserController {
    
        @Autowired
        public IUserService userService;
        @Resource
        private RedisUtils redisUtils;

        @MyLog(value = "用户登录")
        @PostMapping("/login")
        public Result login(@Valid @RequestBody UserDTO userDTO){
                String username = userDTO.getUsername();
                String password = userDTO.getPassword();
                if(StrUtil.isBlank(username)||StrUtil.isBlank(password)){
                        return Result.error(Constants.CODE_400,"参数错误");
                }
                UserDTO dto = userService.login(userDTO);
                //token存入redis
                redisUtils.add(dto.getUsername(),dto.getToken(),1, TimeUnit.DAYS);
                return Result.success(dto);
        }

        @MyLog(value = "用户注册")
        @PostMapping("/register")
        public Result register (@Valid @RequestBody UserDTO userDTO){
                String username = userDTO.getUsername();
                String password = userDTO.getPassword();
                if(StrUtil.isBlank(username)||StrUtil.isBlank(password)){
                        return Result.error(Constants.CODE_400,"参数错误");
                }
                return Result.success(userService.register(userDTO));
        }

        @MyLog(value = "修改密码名称")
        @PostMapping("/editPassword")
        public Result  editPassword(@RequestBody User user){
                User oldUser=userService.getById(user.getId());
                QueryWrapper<User> queryWrapper=new QueryWrapper<>();
                MD5 md5 = new MD5();
                String userPassword = md5.digestHex(user.getPassword());
                user.setPassword(userPassword);
                queryWrapper.eq("username",user.getUsername());
                User one=userService.getOne(queryWrapper);

                if(oldUser.getUsername().equals(user.getUsername())){
                        oldUser.setUsername(user.getUsername());
                        oldUser.setPassword(user.getPassword());
                        userService.updateById(oldUser);
                        return Result.success("修改成功");
                }

                if(one!=null){
                       return Result.error(Constants.CODE_600,"用户已存在");
                }else{
                        oldUser.setUsername(user.getUsername());
                        oldUser.setPassword(user.getPassword());
                        userService.updateById(oldUser);
                        return Result.success("修改成功");
                }
        }

        // 新增或者更新
        @MyLog(value = "添加或修改用户")
        @PostMapping
        public Result save(@RequestBody User user) {
                Integer userId=user.getId();

                if(userId==null) {
                        String username = user.getUsername();
                        MD5 md5 = new MD5();
                        String userPassword = md5.digestHex(user.getPassword());
                        user.setPassword(userPassword);
                        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("username", username);
                        User one = userService.getOne(queryWrapper);
                        if(one!=null){
                                return Result.error(Constants.CODE_600,"用户已存在");
                        }else {
                                return Result.success(userService.save(user));
                        }
                }else{
                        User oneUser=userService.getById(userId);
                        if(oneUser.getUsername().equals(user.getUsername())){
                                return Result.success(userService.updateById(user));
                        }else{
                                String username = user.getUsername();
                                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("username", username);
                                User one = userService.getOne(queryWrapper);
                                if(one!=null){
                                        return Result.error(Constants.CODE_600,"用户已存在");
                                }else{
                                        return Result.success(userService.updateById(user));
                                }
                        }

                }

                }

        @MyLog(value = "单个删除用户")
        @DeleteMapping("/{id}")
        public Result delete(@PathVariable Integer id) {
                User currentUser = JwtUtil.getCurrentUser();
                Integer userId=currentUser.getId();
                if(id.equals(userId)){
                        return Result.error(Constants.CODE_600,"用户已登录，无法删除");
                }
                return Result.success(userService.removeById(id));
                }


        @MyLog(value = "批量删除用户")
        @PostMapping("/del/batch")
        public Result deleteBatch(@RequestBody List<Integer> ids) {
                User currentUser = JwtUtil.getCurrentUser();
                Integer userId=currentUser.getId();
                if(ids.contains(userId)){
                        return Result.error(Constants.CODE_600,"用户已登录，无法删除");
                }
                return Result.success(userService.removeByIds(ids));
                }

        @MyLog(value = "查询所有用户")
        @GetMapping
        public Result findAll() {return Result.success(userService.list());}

        @MyLog(value = "查询单个用户")
        @GetMapping("/{id}")
        public Result findOne(@PathVariable Integer id) {
                return Result.success(userService.getById(id));
                }

        @MyLog(value = "获取用户个人信息")
        @GetMapping("/username/{username}")
        public Result findOne(@PathVariable String username) {
                QueryWrapper<User> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("username",username);
                return Result.success(userService.getOne(queryWrapper));
        }

        @MyLog(value = "分页查询用户")
        @GetMapping("/page")
        public Result findPage(@RequestParam Integer pageNum,
                                   @RequestParam Integer pageSize,
                                   @RequestParam(defaultValue = "") String username) {
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                if (!"".equals(username)) {
                        queryWrapper.like("username", username);
                }
                //获取当前用户信息
                User currentUser = JwtUtil.getCurrentUser();
                System.out.println("用户昵称======"+currentUser.getNickname());
              //  queryWrapper.orderByDesc("id");
                return Result.success(userService.page(new Page<>(pageNum, pageSize), queryWrapper));
                }
        /**
         * 导出接口
         */

        @MyLog(value = "导出用户信息")
        @GetMapping("/export")
        public void export(HttpServletResponse response) throws Exception {

                // 从数据库查询出所有的数据
                List<User> list = userService.listUser();
                // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
                // 在内存操作，写出到浏览器
                ExcelWriter writer = ExcelUtil.getWriter(true);
                writer.addHeaderAlias("id", "ID");
                writer.addHeaderAlias("username", "用户名");
                writer.addHeaderAlias("nickname", "昵称");
                writer.addHeaderAlias("email", "邮箱");
                writer.addHeaderAlias("phone", "电话");
                writer.addHeaderAlias("address", "地址");



                writer.write(list, true);

                // 设置浏览器响应的格式
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
                String fileName = URLEncoder.encode("用户信息", "UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

                ServletOutputStream out = response.getOutputStream();
                writer.flush(out, true);
                out.close();
                writer.close();

        }

}

